from base.connection import get_db_session
from common.wtm.WxTemplateMessage import STMessage
from common.definition import AgencyType, OrderType
from conf import config
from conf.config import DOMAIN
from conf.promotion import NEW_CUSTOMER_PROMO_GOODS_ID
import datetime
from decimal import Decimal
import logging

logger = logging.getLogger("wechat")


def balance_notice(touser, money, msg, remark):
    """
    充值成功提醒
        {{first.DATA}}
        充值金额：{{keyword1.DATA}}
        充值时间：{{keyword2.DATA}}
        账户总额：{{keyword3.DATA}}
        {{remark.DATA}
    :param touser:
    :param money:
    :return:
    """
    logger.info(f"执行余额奖励通知: to_user={touser}")

    try:
        class AccountMoney(object):
            pass

        session = get_db_session([
            {"db_table": "ebt_account_money", "model": AccountMoney},
        ])

        am = session.query(AccountMoney).filter_by(ebf_am_user_id=touser).first()
        if am:
            am_money = str(am.ebf_am_money.quantize(Decimal("0.00")))
            data = {
                "first": {
                    "value": msg,
                    "color": "#3990eb"
                },
                "keyword1": {
                    "value": str(money) + "元",
                    "color": "#fe5627"
                },
                "keyword2": {
                    "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                    "color": "#3990eb"
                },
                "keyword3": {
                    "value": am_money + "元",
                    "color": "#3990eb"
                },
                "remark": {
                    "value": remark,
                    "color": "#3990eb"
                }
            }
            template_id = config.TM_BALANCE_SUCCESS
            url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/app1/index.html#/balance"
            topcolor = "#fe5627"
            counter = 1
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info(f"OK: 余额奖励通知发送成功, touser={touser}, money={money}")
                    flag = False
                elif str(resp) == "43004":
                    logger.info(f"NG: 余额奖励通知发送失败, 用户已取消关注 touser={touser}, money={money}")
                    flag = False
                else:
                    logger.error(f"NG: 余额奖励通知发送失败, errcode={resp} touser={touser}, money={money}")
                counter += 1
        else:
            logger.error(f"NG: 余额账号未开通, touser={touser}, money={money}")
    except Exception as e:
        logger.exception(e)


def daily_benefit_notice(fee, touser, order_id, first):
    """
    合伙人每日收益返还通知
    返利到帐提醒
        {{first.DATA}}
        金额：{{keyword1.DATA}}
        时间：{{keyword2.DATA}}
        {{remark.DATA}}
    :param touser:
    :param fee:
    :return:
    """
    logger.info("start sending daily_benefit_notice: oid: %s, order_id=%s" % (touser, order_id))
    try:
        money = str(fee)
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": money + "元",
                "color": "#fe5627"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": "",
                "color": "#3990eb"
            }
        }
        template_id = config.TM_REWARDED
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/partners3/index.html#/index"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK：合伙人每日收益返还通知 oid: %s fee：%s, order_id=%s" % (touser, money, order_id))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG:用户已取消关注,每日收益返还通知发送失败 oid: %s, order_id=%s" % (touser, order_id))
                flag = False
            else:
                logger.error("NG: 合伙人每日收益返还通知 errcode=%s, oid=%s, order_id=%s" % (resp, touser, order_id))
            counter += 1
    except Exception as e:
        logger.exception(e)


def goods_shipped_notice(id, express_name, express_number, touser):
    """
    商城订单发货提醒
        {{first.DATA}}
        订单编号：{{keyword1.DATA}}
        物流公司：{{keyword2.DATA}}
        物流单号：{{keyword3.DATA}}
        {{remark.DATA}}
    :param id:
    :param express_name:
    :param express_number:
    :param touser:
    :return:
    """
    logger.info("执行发货通知: order_id=%s" % id)
    try:
        first = "您购买的商品已经发货啦！"
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": id,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": express_name,
                "color": "#3990eb"
            },
            "keyword3": {
                "value": express_number,
                "color": "#3990eb"
            },
            "remark": {
                "value": "【请先验货，再签收】发现破损，请第一时间联系客服 18926405852(微信同号) 或拒收!" +
                         "\n" + "点击查看订单物流详情，第一时间了解商品动态>>",
                "color": "#3990eb"
            }
        }
        template_id = config.TM_ORDER_SHIPPED
        url = f"https://{DOMAIN}/static/app/index.html#/express-info/" + id
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 发货提醒发送成功： order_id=%s" % id)
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 发货提醒发送失败，原因用户已取消关注： order_id=%s" % id)
                flag = False
            else:
                logger.exception("NG: 发货提醒发送失败： order_id=%s, errcode=%s" % (id, resp))
            counter += 1
    except Exception as e:
        logger.exception(e)


def daily_share_out_bonus_notice(touser, fee):
    """
    合伙人每日共享分红通知
    返利到帐提醒
        {{first.DATA}}
        金额：{{keyword1.DATA}}
        时间：{{keyword2.DATA}}
        {{remark.DATA}}
    :param touser:
    :param fee:
    :return:
    """
    logger.info("执行合伙人每日共享分红通知: oid=%s" % touser)
    try:
        data = {
            "first": {
                "value": "财从天降，您的合伙人共享分红已到账！所有合伙人每天均分莱支好酒销售总额的5%:",
                "color": "#3990eb"
            },
            "keyword1": {
                "value": f"{fee}元",
                "color": "#fe5627"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": "点击 <分享有礼> 推广莱支好酒，最高40%返佣，分红可提现或消费。",
                "color": "#3990eb"
            }
        }
        template_id = config.TM_REWARDED
        url = f"https://{DOMAIN}/go?url=/static/partners/index.html#/partnerAdd?oid=" + touser
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK：平台共享收益通知 oid: %s fee：%s" % (touser, fee))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 平台共享收益通知，原因用户已取消关注： oid=%s" % touser)
                flag = False
            else:
                logger.error("NG: 平台共享收益通知 errcode=%s, oid=%s" % (resp, touser))
            counter += 1
    except Exception as e:
        logger.exception(e)


def new_customer_gift_order_reward_notice(touser, order_id, fee):
    """
    新人礼订单奖励通知
    返利到帐提醒
        {{first.DATA}}
        金额：{{keyword1.DATA}}
        时间：{{keyword2.DATA}}
        {{remark.DATA}}
    :param touser:
    :param fee:
    :return:
    """
    logger.info(f"执行新人礼订单奖励通知: open_id={touser}, {order_id=}, money={fee}")
    try:
        data = {
            "first": {
                "value": "恭喜您推荐的新人已成功半价购买新人礼套装，奖励您30元奖金可秒提现到微信钱包！",
                "color": "#3990eb"
            },
            "keyword1": {
                "value": f"{fee}元",
                "color": "#fe5627"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": f"订单尾号[{str(order_id)[-4:]}] 点击详情到【我的奖金】页面提现。推荐新人越多、奖励机会越多。",
                "color": "#3990eb"
            }
        }
        template_id = config.TM_REWARDED
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/app1/index.html#/balance"

        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 新人礼订单奖励通知 open_id={touser}, order_id={order_id}, money={fee}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 新人礼订单奖励通知 原因: 用户已取消关注 open_id={touser}, order_id={order_id}, money={fee}")
                flag = False
            else:
                logger.error(f"NG: 新人礼订单奖励通知 errcode={resp}, open_id={touser}, order_id={order_id}, money={fee}")
            counter += 1
    except Exception as e:
        logger.exception(e)


def order_benefit_notice(first, order_id, order_fee_str, benefit, open_id, time, agency_type=AgencyType.NORMAL):
    """
    商城订单收益通知
    收益提醒
        {{first.DATA}}
        订单号：{{keyword1.DATA}}
        订单金额：{{keyword2.DATA}}
        收益金额：{{keyword3.DATA}}
        时间：{{keyword4.DATA}}
        {{remark.DATA}}

    :param first:
    :param order_id:
    :param order_fee_str: 订单金额字符串
    :param benefit:
    :param open_id:
    :param time:
    :param agency_type:
    :return:
    """
    logger.info("执行订单收益通知: order_id=%s, oid=%s" % (order_id, open_id))
    try:
        bf = Decimal(benefit)
        if bf <= Decimal(0):
            return
        b1 = str((bf * Decimal(0.8)).quantize(Decimal("0.00")))
        b2 = str((bf * Decimal(0.2)).quantize(Decimal("0.00")))
        bf_str = str(bf.quantize(Decimal("0.00")))
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": order_id,  # 订单号
                "color": "#3990eb"
            },
            "keyword2": {
                "value": order_fee_str,  # 订单金额字符串
                "color": "#3990eb"
            },
            "keyword3": {
                "value": bf_str + "元",  # 收益金额
                "color": "#fe5627"
            },
            "keyword4": {
                "value": time,  # 收益创建时间
                "color": "#3990eb"
            },
            "remark": {
                "value": "努力越多，收益越高，佣金可提现或消费！",
                "color": "#fe5627"
            }
        }
        touser = open_id
        template_id = config.TM_BENEFIT_NOTICE
        if agency_type == AgencyType.STORE or agency_type == AgencyType.CLERK:
            url = f"https://{DOMAIN}/admin/partner"
        else:
            url = f"https://{DOMAIN}/admin/partner"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 收益通知发送成功 trade_no=%s, oid=%s" % (order_id, open_id))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 收益通知发送失败,用户已取消关注 trade_no=%s, oid=%s" % (order_id, open_id))
                flag = False
            else:
                logger.error("NG:收益通知发送失败 errcode=%s, trade_no=%s, oid=%s" % (resp, order_id, open_id))
            counter += 1
    except Exception as e:
        logger.exception(e)


def partner_join_notice(touser, first, agency_id, name, remark=None):
    """
    加盟成功通知
        {{first.DATA}}
        编号：{{keyword1.DATA}}
        姓名：{{keyword2.DATA}}
        {{remark.DATA}}

    :param touser:
    :param first:
    :param agency_id:
    :param name:
    :param remark:
    :return:
    """
    logger.info("执行加盟成功通知: name=%s, touser=%s" % (name, touser))

    if not isinstance(touser, list):
        touser = [touser]

    if not remark:
        remark = "邀请好友喝好酒，一起分享多受益！"

    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": agency_id,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": name,
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }

        template_id = config.TM_JOIN_SUCCESS
        url = f"https://{DOMAIN}/admin/partner"
        topcolor = "#fe5627"

        for user in touser:
            counter = 1
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(user, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info("OK: 加盟成功通知发送成功 name=%s, touser=%s" % (name, user))
                    flag = False
                elif str(resp) == "43004":
                    logger.info("NG: 加盟成功通知发送失败,用户已取消关注 name=%s, touser=%s" % (name, user))
                    flag = False
                else:
                    logger.error("NG:加盟成功通知发送失败 errcode=%s, name=%s, touser=%s" % (resp, name, user))
                counter += 1
    except Exception as e:
        logger.exception(e)


def audit_pass_notice(level, touser):
    """
    审核成功通知
        {{first.DATA}}
        获得奖励：{{keyword1.DATA}}
        审核时间：{{keyword2.DATA}}
        {{remark.DATA}}
    :param level:
    :param touser:
    :return:
    """
    logger.info("执行审核成功奖励一元通知: touser=%s" % touser)
    try:
        data = {
            "first": {
                "value": "恭喜您入驻" + '“' + level + '”' + " 审核成功！",
                "color": "#3990eb"
            },
            "keyword1": {
                "value": "1.00元",
                "color": "#fe5627"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": "奖励已入您的收益账户，点击查看奖励及提现！【分享越多，收益越高】",
                "color": "#3990eb"
            }
        }
        template_id = "vAfl9k9mEgrEoMn3CaQq4J6aUR_4R_MmwWZj3iDfDOs"
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/partners3/index.html#/index"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 审核发送成功 touser=%s" % touser)
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 审核通知发送失败,用户已取消关注 touser=%s" % touser)
                flag = False
            else:
                logger.error("NG: 审核通知发送失败 errcode=%s, touser=%s" % (resp, touser))
            counter += 1
    except Exception as e:
        logger.exception(e)


def balance_reward_notice(touser, money, trade_no, am_money, first):
    """
    推荐用户购酒奖励17元余额
    充值成功提醒
        {{first.DATA}}
        充值金额：{{keyword1.DATA}}
        充值时间：{{keyword2.DATA}}
        账户总额：{{keyword3.DATA}}
        {{remark.DATA}
    :param touser:
    :param money:
    :param trade_no:
    :param am_money:
    :param first:
    :return:
    """
    logger.info("执行余额奖励通知: touser=%s, order_id=%s" % (touser, trade_no))
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": str(money) + "元",
                "color": "#fe5627"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "keyword3": {
                "value": am_money + "元",
                "color": "#3990eb"
            },
            "remark": {
                "value": "多多分享，多多受益！",
                "color": "#3990eb"
            }
        }
        template_id = config.TM_BALANCE_SUCCESS
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/app/index.html#/personal"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 余额奖励通知发送成功 touser=%s, order_id=%s" % (touser, trade_no))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 余额奖励通知发送失败,用户已取消关注 touser=%s, order_id=%s" % (touser, trade_no))
                flag = False
            else:
                logger.error("NG: 余额奖励通知发送失败 errcode=%s, touser=%s, order_id=%s" % (resp, touser, trade_no))
            counter += 1
    except Exception as e:
        logger.exception(e)


def buy_success_notice(touser, trade_no):
    """
    购买成功通知
        {{first.DATA}}
        商品名称：{{keyword1.DATA}}
        消费金额：{{keyword2.DATA}}
        购买时间：{{keyword3.DATA}}
        {{remark.DATA}}
    :param touser:
    :param trade_no:
    :return:
    """
    logger.info("执行购买成功通知: touser=%s, order_id=%s" % (touser, trade_no))
    try:
        remark = "点击《分享有礼》分享好友参加尝鲜活动，成功一个奖励17元到余额账户用于消费，邀请越多，奖励越多，从今喝酒不花钱！"
        data = {
            "first": {
                "value": "邀请好友参加尝鲜活动，成功一个奖励17元",
                "color": "#fe5627"
            },
            "keyword1": {
                "value": "格调人生干红LI尝鲜礼2支装",
                "color": "#3990eb"
            },
            "keyword2": {
                "value": "99元",
                "color": "#fe5627"
            },
            "keyword3": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = "BeBtcmxYV9FNVmS6DtkChDrACjHVXVmGD7vhVgWuNqs"
        url = f"https://{DOMAIN}/user/promotion"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 购买成功通知发送成功 touser=%s, order_id=%s" % (touser, trade_no))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 购买成功通知发送失败,用户已取消关注 touser=%s, order_id=%s" % (touser, trade_no))
                flag = False
            else:
                logger.error("NG: 购买成功通知发送失败 errcode=%s, touser=%s, order_id=%s" % (resp, touser, trade_no))
            counter += 1
    except Exception as e:
        logger.exception(e)


def number_remind_notice(touser, no, nickname):
    """
    编号领取提醒
        {{first.DATA}}
        昵称：{{keyword1.DATA}}
        编号：{{keyword2.DATA}}
        说明：{{keyword3.DATA}}
        时间：{{keyword4.DATA}}
        {{remark.DATA}}
    :param touser:
    :param no:
    :param nickname:
    :return:
    """
    logger.info("执行编号提醒通知: touser=%s, number=%s" % (touser, no))
    title1 = "嗨，你来啦~\n欢迎加入17°恒温红酒俱乐部，作为恒温红酒开创者，除了酒庄全程恒温直供佳酿，"
    title2 = "还有不限次免费酒卡、全球酒庄自驾游大奖等您领……"
    first = title1 + title2
    explanation = "新人即送100元购酒券，编号尾号逢9再赠酒一支"
    remark = "购酒券可线上或店内购酒，逢9赠酒限到店领取（查看详情-选择门店-下单0元付款-出示给店员领酒）"
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": nickname,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": no,
                "color": "#fe5627"
            },
            "keyword3": {
                "value": explanation,
                "color": "#3990eb"
            },
            "keyword4": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_NUMBER_REMIND
        if no.endswith("9"):
            url = f"https://{DOMAIN}/wx/template/message?title=number_remind"
        else:
            url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/store/index.html"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 编号提醒通知发送成功 touser=%s, number=%s" % (touser, no))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 编号提醒通知发送失败,用户已取消关注 touser=%s, number=%s" % (touser, no))
                flag = False
            else:
                logger.error("NG: 编号提醒通知发送失败 errcode=%s, touser=%s, number=%s" % (resp, touser, no))
            counter += 1
    except Exception as e:
        logger.exception(e)


def benefit_reward_notice(first, key, touser, money, order_id, is_agency=True):
    """
    合伙人结算通知
        {{first.DATA}}
        收益类型：{{keyword1.DATA}}
        收益金额：{{keyword2.DATA}}
        收益时间：{{keyword3.DATA}}
        {{remark.DATA}}
    :param first:
    :param key:
    :param touser:
    :param money:
    :param order_id:
    :param is_agency:
    :return:
    """
    logger.info("执行收益奖励通知: touser=%s, money=%s, order_id=%s" % (touser, money, order_id))

    url = f"https://{DOMAIN}/admin/partner"
    remark = f"单号:{order_id} 邀请好友喝好酒，一起分享多收益！"
    if key == "新店酬宾奖励":
        key = "分店开业酬宾—分享奖励红包"
        url = f"https://{DOMAIN}/wx/promotion"
        remark = "点击链接领券抢购开店酬宾礼包，然后分享活动海报，邀成一人奖100，两人奖200元秒到账秒提现，实际到手价99元/箱。"
        if money == 100:
            url = f"https://{DOMAIN}/go?url=/static/app1/index.html#/withdraw"
            remark = f"点击【查看详情】可提现秒到账，邀满2人奖励200元即止；可复购复送红包。"
    elif key == "邀请联营店主奖励":
        remark = f"请及时培训新店主！单号: {order_id}"
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": key,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": str(money) + "元",
                "color": "#fe5627"
            },
            "keyword3": {
                "value": datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M:%S"),
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_BENEFITED

        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 收益奖励通知发送成功touser=%s, money=%s, order_id=%s" % (touser, money, order_id))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 奖励通知发送失败,用户已取消关注touser=%s, money=%s, order_id=%s" % (touser, money, order_id))
                flag = False
            else:
                logger.error("NG: 收益奖励通知发送失败 errcode=%s, touser=%s, order_id=%s" % (resp, touser, order_id))
            counter += 1
    except Exception as e:
        logger.exception(e)


def pay_success_notice(touser, order_id, count, fee, describe, is_self=True, name=None):
    """
    购买成功通知
        {{first.DATA}}
        商品名称：{{keyword1.DATA}}
        消费金额：{{keyword2.DATA}}
        购买时间：{{keyword3.DATA}}
        {{remark.DATA}}
    :param touser:
    :param order_id:
    :param count:
    :param fee:
    :param describe:
    :param is_self:
    :param name:
    :return:
    """
    logger.info("执行加盟费订单支付成功通知: touser=%s, order_id=%s, fee=%s" % (touser, order_id, fee))
    if not is_self:
        value_one = '恭喜您邀请的"' + name + '"参与托管经营成功！'
        value_two = "托管经营（" + str(count) + "份）"
    elif describe == "crowdfunding":
        value_one = "您的订单已支付成功，次日起两年内每天共享收益分红，赠送的红酒将恒温配送到您手上！"
        value_two = "托管经营（" + str(count) + "份）"
    elif describe == "online":
        value_one = "支付成功！"
        value_two = "成功参与线上分享"
    elif describe == "online1":
        value_one = "支付成功！"
        value_two = "合伙人专享爆款样酒款"
    elif describe == "online2":
        value_one = "支付成功！"
        value_two = "合伙人专享爆款样酒款"
    elif describe in ["underline", "delegate", "partnershop"]:
        if describe == "underline":
            title = "线下开店"
        elif describe == "partnershop":
            title = "联合经营"
        else:
            title = "委托经营"
        value_one = "支付成功！"
        value_two = "成功参与" + title
    elif describe == "adfunding":
        value_one = "您已成功参与共享广告点位众筹！"
        value_two = "共享广告点位众筹（" + str(count) + "份）"

    try:
        data = {
            "first": {
                "value": value_one,
                "color": "#fe5627"
            },
            "keyword1": {
                "value": value_two,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": str(fee) + "元",
                "color": "#fe5627"
            },
            "keyword3": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": "感谢您的支持！现在分享给好友且成功参与活动，即可收获惊喜大礼！",
                "color": "#3990eb"
            }
        }
        template_id = config.TM_BUY_SUCCESS
        if describe == "adfunding":
            url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/app/index.html#/myOrder"
        else:
            url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/partners3/index.html#/index"
        topcolor = "#fe5627"
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 支付成功通知发送成功 touser=%s, order_id=%s, fee=%s" % (touser, order_id, fee))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 支付成功通知发送失败,用户已取消关注touser=%s, order_id=%s, fee=%s" % (touser, order_id, fee))
                flag = False
            else:
                logger.error("NG: 支付成功通知发送失败errcode=%s, touser=%s, order_id=%s" % (resp, touser, order_id))
            counter += 1
    except Exception as e:
        logger.exception(e)


def add_stock_notice(first, touser, store_name, goods_name, count, store_id):
    """
    商品库存不足通知
        {{first.DATA}}
        店铺名称：{{keyword1.DATA}}
        商品名称：{{keyword2.DATA}}
        库存数量：{{keyword3.DATA}}
        {{remark.DATA}}
    :param first:
    :param touser:
    :param store_name:
    :param goods_name:
    :param count:
    :param store_id:
    :return:
    """
    logger.info("add_stock_notice: sotre_id=%s, goods_name=%s" % (store_id, goods_name))
    value = "请尽快补充库存并更新门店系统库存数据！"
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": store_name + "(" + str(store_id) + ")",
                "color": "#3990eb"
            },
            "keyword2": {
                "value": goods_name,
                "color": "#3990eb"
            },
            "keyword3": {
                "value": str(count),
                "color": "#fe5627"
            },
            "remark": {
                "value": value,
                "color": "#3990eb"
            }
        }
        template_id = "fuBMkipddCS-VABSW4wEtOojTT7G8D0yolHTZzt3NyI"
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/mall"
        topcolor = "#fe5627"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 库存不足通知发送成功: sotre_id=%s, goods_name=%s" % (store_id, goods_name))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 库存不足通知发送失败,用户取消关注: touser=%s, sotre_id=%s" % (touser, store_id))
                flag = False
            else:
                logger.error("NG: 库存不足通知发送失败: sotre_id=%s, goods_name=%s" % (store_id, goods_name))
            counter += 1
    except Exception as e:
        logger.exception(e)


def new_order_notice(touser, first, trade_no, time, goods, address, remark, url):
    """
    新订单通知模版消息

        {{first.DATA}}
        订单编号：{{keyword1.DATA}}
        下单时间：{{keyword2.DATA}}
        商品名称：{{keyword3.DATA}}
        配送地址：{{keyword4.DATA}}
        {{remark.DATA}}

    :param touser:
    :param trade_no:
    :return:
    """
    logger.info(f"执行新订单通知: touser={touser}, order_id={trade_no}")
    try:
        data = {
            "first": {
                "value": first,
                "color": "#fe5627"
            },
            "keyword1": {
                "value": trade_no,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": time,
                "color": "#3990eb"
            },
            "keyword3": {
                "value": goods,
                "color": "#3990eb"
            },
            "keyword4": {
                "value": address,
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_NEW_ORDER
        topcolor = "#fe5627"
        # url = url

        if not isinstance(touser, list):
            touser = [touser]

        for user in touser:
            counter = 1
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(user, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info("OK: 新订单通知发送成功 touser=%s, order_id=%s" % (user, trade_no))
                    flag = False
                elif str(resp) == "43004":
                    logger.info("NG: 新订单通知发送失败, 用户已取消关注 touser=%s, order_id=%s" % (user, trade_no))
                    flag = False
                else:
                    logger.error("NG: 新订单通知发送失败 errcode=%s, touser=%s, order_id=%s" % (resp, user, trade_no))
                counter += 1
    except Exception as e:
        logger.exception(e)


def new_order_notice0(touser, room_id, store_id, order_id, first=None, value=None):
    """
    新订单提醒
        {{first.DATA}}
        订单编号：{{keyword1.DATA}}
        时间：{{keyword2.DATA}}
        {{remark.DATA}}
    :param touser:
    :param room_id:
    :param store_id:
    :param order_id:
    :param first:
    :param value:
    :return:
    """
    logger.info("new_order_notice0: sotre_id=%s, order_id=%s" % (store_id, order_id))
    if not first:
        first = "有新的订单，请到订单列表查看！"

    if not value:
        value = "请及时接单并尽快配送！【序号：%s】" % room_id
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": order_id,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": value,
                "color": "#3990eb"
            }
        }
        template_id = "OGax-7WepXm6Ivrn01yvWiZf4uxUIVupTbsunLr0S8g"
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/storebackstage/index.html"
        topcolor = "#fe5627"
        if not isinstance(touser, list):
            touser = [touser]

        for t in touser:
            counter = 0
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(t, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info(f"OK: 新订单提醒成功: sotre_id={store_id}, order_id={order_id}, oid={t}")
                    flag = False
                elif str(resp) == "43004":
                    logger.info(f"NG: 新订单提醒失败,原因用户取消关注: sotre_id={store_id}, order_id={order_id}, oid={t}")
                    flag = False
                else:
                    logger.error(f"NG: 新订单提醒失败: sotre_id={store_id}, order_id={order_id}, oid={t}")
                counter += 1
    except Exception as e:
        logger.exception(e)


def refund_application_notice(touser, order_id, goods, order_fee, first=None, remark=None):
    """
    退货申请提醒
        {{first.DATA}}
        订单编号：{{keyword1.DATA}}
        商品名称：{{keyword2.DATA}}
        订单金额：{{keyword3.DATA}}
        {{remark.DATA}}

    :param touser
    :param order_id
    :param goods
    :param order_fee
    :param first
    :param remark
    :return:
    """

    if not first:
        first = "买家申请退货，请及时审核。"

    try:
        data = {
            "first": {
                "value": first,
                "color": "#fe5627"
            },
            "keyword1": {
                "value": order_id,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": goods,
                "color": "#3990eb"
            },
            "keyword3": {
                "value": order_fee,
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_REFUND_APPLICATION
        url = f"https://{DOMAIN}/user/account"
        topcolor = "#fe5627"

        if not isinstance(touser, list):
            touser = [touser]

        for t in touser:
            counter = 0
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(t, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info(f"OK: 退货提醒成功: order_id={order_id}, oid={t}")
                    flag = False
                elif str(resp) == "43004":
                    logger.info(f"NG: 退货提醒失败,原因用户取消关注: order_id={order_id}, oid={t}")
                    flag = False
                else:
                    logger.error(f"NG: 退货提醒失败: order_id={order_id}, oid={t}")
                counter += 1
    except Exception as e:
        logger.exception(e)


def refund_approval_notice(touser, order_id, goods, order_fee, notes=None, approval="审核通过", first=None, remark=None):
    """
    退货审核通知
        {{first.DATA}}
        审核结果：{{keyword1.DATA}}
        商品信息：{{keyword2.DATA}}
        退货金额：{{keyword3.DATA}}
        审核说明：{{keyword4.DATA}}
        审核时间：{{keyword5.DATA}}
        {{remark.DATA}}

    :param touser
    :param order_id
    :param goods
    :param order_fee
    :param notes
    :param approval
    :param first
    :param remark
    :return:
    """

    if not first:
        first = "买家申请退货，请及时审核。"

    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": approval,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": goods,
                "color": "#3990eb"
            },
            "keyword3": {
                "value": order_fee,
                "color": "#3990eb"
            },
            "keyword4": {
                "value": notes,
                "color": "#3990eb"
            },
            "keyword5": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_REFUND_APPROVAL
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/storebackstage/index.html"
        topcolor = "#fe5627"
        if not isinstance(touser, list):
            touser = [touser]

        for t in touser:
            counter = 0
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(t, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info(f"OK: 退货审核通知发送成功: order_id={order_id}, oid={t}")
                    flag = False
                elif str(resp) == "43004":
                    logger.info(f"NG: 退货审核通知发送失败,原因用户取消关注: order_id={order_id}, oid={t}")
                    flag = False
                else:
                    logger.error(f"NG: 退货审核通知发送失败: order_id={order_id}, oid={t}")
                counter += 1
    except Exception as e:
        logger.exception(e)


def arrival_account_notice(touser, order_id, money, first=None, value=None, remark=None):
    """
    到账提醒: 用于优惠券生效通知用户 (模版失效，勿用）
        {{first.DATA}}
        到账金额：{{keyword1.DATA}}
        到账时间：{{keyword2.DATA}}
        到账详情：{{keyword3.DATA}}
        {{remark.DATA}}
    :param touser:
    :param order_id:
    :param id:
    :param money:
    :param first:
    :param value:
    :param remark:
    :return:
    """
    logger.info(f"arrival_to_account_notice: user_id={touser}, order_id={order_id} money={money}")
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": f"{money}元",
                "color": "#fe5627"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "keyword3": {
                "value": value,
                "color": "#fe5627"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = "TnHdaCokalkrrh4I1DvJkZo6MLnK-tlZtjJppttaHc8"
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/store/index.html#/coupon"
        topcolor = "#fe5627"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 优惠券生效通知发送成功: oid={touser}, coupon_user_id={id}, order_id={order_id}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 优惠券生效通知发送失败,取消关注: oid={touser}, coupon_user_id={id}, order_id={order_id}")
                flag = False
            else:
                logger.error(f"NG: 优惠券生效通知发送失败: oid={touser}, coupon_user_id={id}, order_id={order_id}")
            counter += 1
    except Exception as e:
        logger.exception(e)


def coupon_received_notice(touser, coupon_name, coupon_type="代金券", create_time=None, expire_time=None, remark=None):
    """
    优惠券到账通知

    优惠券名称 {{thing1.DATA}}
    优惠券类型 {{thing4.DATA}}
    到账时间  {{time5.DATA}}
    有效期至  {{time7.DATA}}
    温馨提示  {{thing8.DATA}}
    :param touser:
    :param coupon_name:
    :param coupon_type:
    :param create_time:
    :param expire_time:
    :param remark:
    :return:
    """
    logger.info(f"coupon_received_notice: user_id={touser} coupon={coupon_name}")
    if not create_time:
        create_time = datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日')
    try:
        data = {
            "thing1": {
                "value": coupon_name,
                "color": "#3990eb"
            },
            "thing4": {
                "value": coupon_type,
                "color": "#fe5627"
            },
            "time5": {
                "value": create_time,
                "color": "#3990eb"
            },
            "time7": {
                "value": expire_time,
                "color": "#fe5627"
            },
            "thing8": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.SM_COUPON_RECEIVED
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/store/index.html#/coupon"
        topcolor = "#fe5627"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 优惠券到账通知发送成功: oid={touser}, coupon={coupon_name}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 优惠券到账通知发送失败,取消关注: oid={touser}, coupon={coupon_name}")
                flag = False
            else:
                logger.error(f"NG: 优惠券到账通知发送失败: oid={touser}, coupon={coupon_name}")
            counter += 1
    except Exception as e:
        logger.exception(e)


def cancel_order_notice(touser, order_id, fee, goods_text, address, reason, first=None, remark=None, url=None):
    """
    订单取消通知: 用于美团主动取消订单配送通知用户
        {{first.DATA}}
        订单金额：{{orderProductPrice.DATA}}
        商品详情：{{orderProductName.DATA}}
        收货信息：{{orderAddress.DATA}}
        订单编号：{{orderName.DATA}}
        {{remark.DATA}}
    :param touser:
    :param order_id:
    :param fee:
    :param goods_text:
    :param address:
    :param reason:
    :return:
    """
    logger.info(f"cancel_order_notice: oid={touser}, order_id={order_id}")
    try:
        if not first:
            first = f"抱歉，因【{reason}】美团已取消配送，由此给您带来的不便敬请谅解！"
        if not remark:
            remark = f"系统已自动申请退款，等待商家确认，如半小时后未收到退款，请电话联系莱支好酒客服！\n客服电话: 18926405852(微信同号)"
        if not url:
            url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/store/index.html#/myOrder"
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "orderProductPrice": {
                "value": f"{fee}元",
                "color": "#fe5627"
            },
            "orderProductName": {
                "value": goods_text,
                "color": "#3990eb"
            },
            "orderAddress": {
                "value": address,
                "color": "#3990eb"
            },
            "orderName": {
                "value": order_id,
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_ORDER_CANCELLED
        topcolor = "#3990eb"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 订单取消通知发送成功: oid={touser}, order_id={order_id}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 订单取消通知发送失败,取消关注: oid={touser}, order_id={order_id}")
                flag = False
            else:
                logger.error(f"NG: 订单取消通知发送失败: oid={touser}, order_id={order_id}")
            counter += 1
    except Exception as e:
        logger.exception(e)


def order_pay_success_notice(touser, order_id, fee, store_id, order_type, first=None, remark=None, url=None):
    """
    订单支付成功提示:
        {{first.DATA}}
        订单编号：{{keyword1.DATA}}
        支付时间：{{keyword2.DATA}}
        支付金额：{{keyword3.DATA}}
        {{remark.DATA}}
    :param touser:
    :param order_id:
    :param fee:
    :param store_id:
    :param order_type:
    :param first:
    :param remark:
    :return:
    """
    logger.info(f"order_pay_success_notice: oid={touser}, order_id={order_id}")
    try:
        base_url = f"https://{DOMAIN}/go?url="
        if not first:
            if order_type == OrderType.GIFT_CARD:
                first = "您的礼品订单支付成功，请及时送出礼品并提醒朋友及时领取！"
            elif order_type == OrderType.NEW_GIFT and store_id == 0:
                first = "礼品领取成功,我们会尽快为您发货！"
            elif order_type == OrderType.NEW_GIFT and store_id > 0:
                first = "礼品领取成功，请在八个小时内到达选定的门店出示订单详情给商家领取礼品，注意：过期无效！"
            elif order_type == OrderType.PINQU:
                first = "您有一笔拼柜订单取酒成功！"
            elif order_type == OrderType.TIYAN:
                first = "您的体验订单支付成功，待激活"
            else:
                first = "您有一笔订单支付成功！"

        if not remark:
            remark = "酒庄直卖，莱支好酒！\n客服电话: 18926405852(微信同号)"
            if order_type == OrderType.PINGUI:
                remark = "订货成功，平台将按发货地址配送！"
            elif order_type == OrderType.TIYAN:
                remark = "请继续邀请朋友一起喝好酒，激活体验订单！\n点击详情去邀请"
            elif order_type == OrderType.GIFT_CARD:
                remark = "如果您的礼品订单24小时内礼品没被领取，系统将自动取消订单并原路退款"

        if not url:
            if order_type == OrderType.PINGUI:
                url = base_url + f"https://{DOMAIN}/static/app/index.html#/myWine"
            elif order_type == OrderType.TIYAN:
                if store_id == 0:
                    # 发送体验订单通知邀请好友跳转
                    url = base_url + f"https://{DOMAIN}/static/app/index.html#/shareQrCode"
                else:
                    # 发送订单失效送优惠券通知跳转
                    url = base_url + f"https://{DOMAIN}/static/app/index.html#/coupon"
            else:
                url = base_url + f"https://{DOMAIN}/order/{order_id}"

        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": order_id,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "keyword3": {
                "value": f"{fee}元",
                "color": "#fe5627"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_ORDER_PAY_SUCCESS
        topcolor = "#3990eb"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 订单支付成功通知发送成功: oid={touser}, order_id={order_id}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 订单支付成功通知发送失败,取消关注: oid={touser}, order_id={order_id}")
                flag = False
            else:
                logger.error(f"NG: 订单支付成功通知发送失败: oid={touser}, order_id={order_id}")
            counter += 1
    except Exception as e:
        logger.exception(e)


def signup_notice(touser, nickname, open_id):
    """
    新用户注册/关注成功通知推荐人

        {{first.DATA}}
        会员昵称：{{keyword1.DATA}}
        关注时间：{{keyword2.DATA}}
        {{remark.DATA}}
    :param touser:
    :param nickname:
    :return:
    """
    logger.info(f"执行用户注册通知: recommend_user={touser}, nickname={nickname} open_id={open_id}")

    data = {
        "first": {
            "value": f"您推荐的新人{nickname}已关注莱支好酒并已获得98元新人礼现金券",
            "color": "#3990eb"
        },
        "keyword1": {
            "value": nickname,
            "color": "#fe5627"
        },
        "keyword2": {
            "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
            "color": "#3990eb"
        },
        "remark": {
            "value": f"现金券7天有效，请提醒TA及时使用，购买新人礼自动扣减98元",
            "color": "#3990eb"
        }
    }

    template_id = config.TM_SUBSCRIBE_SUCCESS

    url = f"https://{DOMAIN}/goods/{NEW_CUSTOMER_PROMO_GOODS_ID}"
    topcolor = "#fe5627"
    try:
        counter = 1
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info("OK: 用户注册通知发送成功, recommend_user=%s, oid=%s" % (touser, open_id))
                flag = False
            elif str(resp) == "43004":
                logger.info("NG: 用户注册通知发送失败,用户已取消关注 recommend_user=%s, oid=%s" % (touser, open_id))
                flag = False
            else:
                logger.error("NG: 用户注册通知发送失败, errcode=%s, recommend_user=%s, oid=%s" % (resp, touser, open_id))
            counter += 1
    except Exception as e:
        logger.exception(e)


def lucky_draw_notice(touser, lucky=None, first=None, remark=None, promotion="用户幸运大奖", award="现金抵扣券", url=None):
    """
    中奖结果通知
        {{first.DATA}}
        活动：{{keyword1.DATA}}
        奖品：{{keyword2.DATA}}
        时间：{{keyword3.DATA}}
        {{remark.DATA}}
    """

    logger.info(f"中奖结果通知: oid={touser}")
    try:
        if not url:
            if not lucky:
                # 领取酒卡
                url = f"https://{DOMAIN}/go?url=/static/winecard/index.html#/getCard"
            elif lucky == "lucky_user":
                # 跳转到新人礼商品详情页
                url = f"https://{DOMAIN}/go?url=/static/app/index.html#/productDetails?goods_id={NEW_CUSTOMER_PROMO_GOODS_ID}"
            elif lucky == "lucky_user_recommender":
                url = f"https://{DOMAIN}/go?url=/static/app1/index.html#/balance"
            elif lucky == "lucky_user_agency":
                url = f"https://{DOMAIN}/go?url=/static/app1/index.html#/myCustomer"
            elif lucky == "recommend_user":
                # 跳转到推荐新人礼商品详情页
                url = f"https://{DOMAIN}/go?url=/static/app/index.html#/productDetails?goods_id=595844098369678"
            elif lucky == "recommend_coupon":
                # 跳转到优惠券
                url = f"https://{DOMAIN}/go?url=/static/app/index.html#/coupon"
            else:
                # 跳转到优惠券
                url = f"https://{DOMAIN}/go?url=/static/app/index.html#/coupon"

        if not first:
            first = "美好的事情已经发生，恭喜您成为莱支好酒推广大使，三个月内凭 “大使酒卡”到莱支好酒任一入驻餐厅就餐，每次每桌赠饮139元干红1瓶。"

        if not remark:
            remark = "点击详情领取“大使酒卡”，作为推广大使，请您分享“我的海报”邀约好友加入17°恒温红酒俱乐部获得神秘奖励，邀请最多前十名大使有机会获得全球酒庄自驾游大奖。"

        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": promotion,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": award,
                "color": "#fe5627"
            },
            "keyword3": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        template_id = config.TM_LUCKY_DRAW
        topcolor = "#3990eb"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 中奖结果通知发送成功: oid={touser}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 中奖结果通知发送失败,取消关注: oid={touser}")
                flag = False
            else:
                logger.error(f"NG: 中奖结果通知发送失败: oid={touser}")
            counter += 1
    except Exception as e:
        logger.exception(e)


def gift_application_notice(touser, first, gift, shop, remark):
    """
    申领成功通知
        {{first.DATA}}
        申领礼品：{{keyword1.DATA}}
        申领时间：{{keyword2.DATA}}
        申领柜台：{{keyword3.DATA}}
        {{remark.DATA}}
    """

    logger.info(f"申领成功通知: oid={touser}")
    try:
        data = {
            "first": {
                "value": first,
                "color": "#3990eb"
            },
            "keyword1": {
                "value": gift,
                "color": "#3990eb"
            },
            "keyword2": {
                "value": datetime.datetime.now().strftime("%Y{y}%m{m}%d{d} %H:%M:%S").format(y='年', m='月', d='日'),
                "color": "#fe5627"
            },
            "keyword3": {
                "value": shop,
                "color": "#3990eb"
            },
            "remark": {
                "value": remark,
                "color": "#3990eb"
            }
        }
        url = f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/app1/index.html#/poster1"
        template_id = config.TM_GIFT_APPLICATION
        topcolor = "#3990eb"
        counter = 0
        flag = True
        while counter < 3 and flag:
            resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
            if resp == "OK":
                logger.info(f"OK: 申领成功通知发送成功: oid={touser}")
                flag = False
            elif str(resp) == "43004":
                logger.info(f"NG: 申领成功通知发送失败,取消关注: oid={touser}")
                flag = False
            else:
                logger.error(f"NG: 申领成功通知发送失败: oid={touser}")
            counter += 1
        return True
    except Exception as e:
        logger.exception(e)
        return False


def template_notice(touser, template_id, url, data, topcolor):
    """
    发送通用模版消息
    """

    logger.info(f"发送模版消息: oid={touser}，id={template_id}, url={url}, data={data}, topcolor={topcolor}")
    try:
        if not isinstance(touser, list):
            users = [touser]
        else:
            users = touser

        for touser in users:
            counter = 0
            flag = True
            while counter < 3 and flag:
                resp = STMessage.SendTemplateMessage(touser, template_id, url, data, topcolor)
                if resp == "OK":
                    logger.info(f"OK: 模版消息发送成功: oid={touser}")
                    flag = False
                elif str(resp) == "43004":
                    logger.info(f"NG: 模版消息发送失败,取消关注: oid={touser}")
                    flag = False
                else:
                    logger.error(f"NG: 模版消息发送失败: oid={touser}")
                counter += 1
        return True
    except Exception as e:
        logger.exception(e)
        return False